const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const userId = wxContext.OPENID;
  
  if (!userId) {
    return {
      code: 1,
      message: '用户未登录'
    };
  }
  
  try {
    const { startTime, endTime, duration, matchedUserId, matchedUserInfo, matchId } = event;
    
    // 参数验证：只要求 matchId，不再要求 matchedUserId/matchedUserInfo
    if (!startTime || !endTime || !duration || !matchId) {
      return {
        code: 2,
        message: '参数不完整'
      };
    }
    
    const now = new Date();
    
    // 创建学习记录
    const recordData = {
      userId,
      startTime,
      endTime,
      duration,
      status: 'not_started', // 未开始
      createTime: now,
      updateTime: now,
      // 学习统计
      actualStartTime: null,
      actualEndTime: null,
      actualDuration: 0,
      breakCount: 0,
      focusScore: 0
    };
    if (matchId) {
      recordData.matchId = matchId;
    }
    const studyRecord = await db.collection('study_records').add({
      data: recordData
    });
    
    return {
      code: 0,
      message: '创建学习记录成功',
      data: {
        studyRecordId: studyRecord._id,
        matchId: matchId || null,
        status: 'not_started',
        startTime,
        endTime,
        duration
      }
    };
  } catch (error) {
    console.error('创建学习记录出错:', error);
    return {
      code: 500,
      message: '服务器错误',
      error: error.message
    };
  }
};